<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/24/24
 * Time: 10:10 AM
 */

namespace App\Console\Commands;

use App\Services\KfAccountService;
use Illuminate\Console\Command;
use App\Models\WechatPush;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\File\File;


/**
 * 企微推送临时素材过期处理
 *
 * Class Push
 * @package App\Console\Commands
 */
class WechatPushMedia extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'push:media';


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '企业微信推送临时素材过期处理';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     *
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        $list = WechatPush::query()->get();
        if ($list->isEmpty()) {

            return false;
        }
        $i       = 0;
        $service = new KfAccountService();
        foreach ($list as $item) {
            $file        = $service->getMedia($item->corp_id, $item->media_id);
            $tmpFilePath = sys_get_temp_dir() . '/' . Str::uuid()->toString();
            file_put_contents($tmpFilePath, file_get_contents($file));
            $tmpFile = new File($tmpFilePath);
            $file    = new UploadedFile(
                $tmpFile->getPathname(),
                $tmpFile->getFilename(),
                $tmpFile->getMimeType(),
                0,
                true
            );
            if (!$data = $service->uploadMedia($item->corp_id, $file)) {
                continue;
            }
            if (!$mediaId = $data['media_id'] ?? '') {
                continue;
            }
            $item->media_id = $mediaId;
            if (!$item->save()) {
                continue;
            }
            $i++;
        }
        Log::info('====>企微推送临时素材过期处理，总计：' . $list->count() . '条，成功：' . $i . '条');
    }
}
